package org.codehaus.activemq.ra;

import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.ResourceAdapter;
import javax.resource.spi.ResourceAdapterAssociation;
import javax.security.auth.Subject;

public class ActiveMQManagedConnectionFactory
  implements ManagedConnectionFactory, ResourceAdapterAssociation
{
  private ActiveMQResourceAdapter adapter;
  private PrintWriter logWriter;

  public void setResourceAdapter(ResourceAdapter adapter)
    throws ResourceException
  {
    this.adapter = ((ActiveMQResourceAdapter)adapter);
  }

  public ResourceAdapter getResourceAdapter()
  {
    return this.adapter;
  }

  public Object createConnectionFactory(ConnectionManager manager)
    throws ResourceException
  {
    return new ActiveMQConnectionFactory(this, manager, this.adapter.getInfo());
  }

  public Object createConnectionFactory()
    throws ResourceException
  {
    return new ActiveMQConnectionFactory(this, new SimpleConnectionManager(), this.adapter.getInfo());
  }

  public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo info)
    throws ResourceException
  {
    return new ActiveMQManagedConnection(subject, this.adapter, (ActiveMQConnectionRequestInfo)info);
  }

  public ManagedConnection matchManagedConnections(Set connections, Subject subject, ConnectionRequestInfo info)
    throws ResourceException
  {
    Iterator iterator = connections.iterator();
    while (iterator.hasNext()) {
      ActiveMQManagedConnection c = (ActiveMQManagedConnection)iterator.next();
      if (c.matches(subject, info)) {
        return c;
      }
    }
    return null;
  }

  public void setLogWriter(PrintWriter logWriter)
    throws ResourceException
  {
    this.logWriter = logWriter;
  }

  public PrintWriter getLogWriter()
    throws ResourceException
  {
    return this.logWriter;
  }
}